import {
  getProductBomOverviewByPage,
  addProductBomOverview,
  updateProductBomOverview,
  delProductBomOverview,
  exportProductBomOverview,
  getProductBomOverviewByBatchProductId,
  addBomByTemplate,
  downloadBomTemplate,
  downloadFile,
  change,
  getMax,
  downloadStandardBom,
  getProductBomOverviewAndReviewByPage,
  postBomReviewByIds,
  getAllVersion,
} from '@/services/design/productBomOverview';
import { viewBaseInfo } from '@/services/product/productManufactInforExecute';
import { addBomReview, delBomReviewByIds } from '@/services/design/bomReview';
import { Ellipsis } from '@/components/Ellipsis';
import {
  PlusOutlined,
  UploadOutlined,
  LogoutOutlined,
  DownOutlined,
  DownloadOutlined,
  ArrowLeftOutlined,
  SaveOutlined,
  EditOutlined,
} from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import '@/pages/design/style.less';
import ProTable from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-components';
import {
  Button,
  Form,
  Input,
  message,
  Modal,
  Tree,
  Upload,
  InputNumber,
  Row,
  Col,
  Select,
  Card,
  Tabs,
} from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
import type { recordInfoType } from './components/interfaceProduct';
import ProductNosubmittedDrawingInfo from './productNosubmittedDrawingInfo';
const ProductNosubmittedBomOverview: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable

  const [modalVisit2, setModalVisit2] = useState(false);
  const [confirmLoading2, setConfirmLoading2] = useState(false);
  const [createOrUpdate2, setCreateOrUpdate2] = useState(false); //编辑框的disable
  const [file, setFile] = useState();
  const [recordInfo, setRecord] = useState<recordInfoType>();
  const [form] = Form.useForm();
  const ref = useRef(null);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly DataSourceType[]>([]);
  const [theversion, setTheversion] = useState(''); // 版本筛选
  const [allversion, setAllversion] = useState([]); // 版本筛选
  const [id_list, setid_list] = useState([]); // 保存修改的id
  const [selections, setSelections] = useState([]); //保存勾选的项目
  const [editingCell, setEditingCell] = useState(null); // 使用state跟踪编辑状态
  const [inputValue, setInputValue] = useState(0); //记录下编辑的数量
  const [reviewWithoutPostId, setReviewWithoutPostId] = useState([]); //记录所有没有被提交过的id
  const [latestVersionDetail, setLatestVersionDetail] = useState({}); //新建的时候必须要使用
  const [maxVersion, setMaxVersion] = useState(''); //最新版本

  const ChangedItemTemplate = {
    bomBeforeId: '',
    bomCode: '',
    bomSequence: null,
    brand: '',
    changeStatus: 0,
    changeSuccess: 0,
    id: '',
    isJia: '',
    isMax: 1,
    materialClassification: '',
    materialCode: '',
    materialName: '',
    materialQty: 0,
    materialSpec: '',
    materialType: '',
    memo: '',
    positionNo: '',
    productCode: '',
    projectName: '',
    unit: '',
    userId: '',
    userName: '',
    version: 0,
    versionSecond: 0,
  };

  type DataSourceType = {
    id: React.Key;
    title?: string;
    readonly?: string;
    decs?: string;
    state?: string;
    created_at?: number;
    update_at?: number;
    children?: DataSourceType[];
  };

  const columns: ProColumns<DataSourceType>[] = [
    // {
    //   title: '序号',
    //   dataIndex: 'index',
    //   valueType: 'index',
    //   width: 80,
    // },
    {
      title: 'BOM编号',
      dataIndex: 'bomCode',
      width: 190,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '版本',
      dataIndex: 'version',
      align: 'center',
      sorter: true,
      render: (text, record) => {
        return <div>{'v' + text + '.' + record.versionSecond}</div>;
      },
    },
    {
      title: '变更状态',
      dataIndex: 'changeStatus',
      align: 'center',
      sorter: true,
      /*       render: (text, record, _, action) => {
        return <div>{record.changeStatus === 0 ? '未变更' : record.changeStatus === 1 ? '已变更' : '已新增'}</div>;
      }, */
      render: (text, record, _, action) => {
        let color = 'status-color-white base-status';
        let word = '原始';
        if (text === 1) {
          color = 'status-color-yellow base-status';
          word = '变更';
        } else if (text === 2) {
          color = 'status-color-green base-status';
          word = '新增';
        }
        return <div className={color}></div>;
      },
    },
    /*     {
      title: '是否最高版本',
      dataIndex: 'isMax',
      // hideInTable: true,
      search: false,
     align: 'center',sorter: true, 
      render: (text, record, _, action) => {
        return <div>{record.isMax === 1 ? '是' : '否'}</div>;
      },
      readonly: true,
      
      defaultSortOrder: 'descend',
    }, */
    /*     {
      title: '是否已提交审批',
      dataIndex: 'isSubmitted',
      search: false,
      align: 'center',
      sorter: true,
      render: (text, record, _, action) => {
        return <div>{text === true ? '是' : '否'}</div>;
      },
    }, */
    {
      title: '物料编码',
      dataIndex: 'materialCode',
      width: 150,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      width: 130,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '物料规格',
      dataIndex: 'materialSpec',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '数量',
      dataIndex: 'materialQty',
      width: 100,
      align: 'center',
      sorter: true,
      valueType: 'digit',
      render: (text, record) => {
        if (record.changeStatus === 1) {
          return (
            <div
              style={{
                display: 'flex',
                alignContent: 'center',
                justifyContent: 'center',
                width: '100%',
                height: '100%',
              }}
            >
              <p style={{ color: 'red', margin: 'auto' }}>{record.preMaterialQty}</p> →{' '}
              <p style={{ color: 'green', margin: 'auto' }}>{text}</p>
            </div>
          );
        }
        if (record.changeStatus === 0 && record.isMax === 1) {
          if (editingCell === record.id) {
            // 编辑状态下显示InputNumber
            return (
              <InputNumber
                value={Number(inputValue)}
                min={0}
                step={1} // 设置步进值为1
                onChange={(value) => setInputValue(value)}
                onBlur={() => {
                  setInputValue(0);
                  setEditingCell(null);
                }} // 失去焦点时取消编辑状态
                onPressEnter={() => handleBlur(record)} // 按下回车键时取消编辑状态
                autoFocus // 自动获取焦点
              />
            );
          } else {
            return (
              <span
                style={{ cursor: 'pointer' }}
                onClick={() => {
                  setEditingCell(record.id);
                  setInputValue(record.materialQty);
                }} // 点击时设置编辑状态
              >
                {text}
                <EditOutlined style={{ color: 'green' }} />
              </span>
            );
          }
        } else {
          return (
            <span
              style={{ cursor: 'pointer' }}
              onClick={() => {
                setEditingCell(record.id);
                setInputValue(record.materialQty);
              }} // 点击时设置编辑状态
            >
              {text}
            </span>
          );
        }
      },
    },
    {
      title: '单位',
      dataIndex: 'unit',
      width: 80,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '位置号',
      dataIndex: 'positionNo',
      width: 100,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '物料品牌',
      dataIndex: 'brand',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '物料分类',
      dataIndex: 'materialClassification',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '物料种类',
      dataIndex: 'materialType',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '是否甲供料',
      dataIndex: 'isJia',
      width: 100,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '产品/柜体编号',
      dataIndex: 'productCode',
      width: 210,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '归档标识',
      dataIndex: 'archiveFlag',
      align: 'center',
      sorter: true,
      render: (text, record, _, action) => {
        return <div>{record.archiveFlag == 1 ? '已归档' : '未归档'}</div>;
      },
      readonly: true,
    },
    // {
    //   title: '产品编码',
    //   dataIndex: 'partCode',
    //   readonly: true,
    // },
    /*  {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 90,
      render: (text, record, _, action) => [
        record.changeStatus != 0 && (
          <a
            key="delete"
            onClick={() => {
              handleDelete(record);
            }}
          >
            删除
          </a>
        ),
                <a
          key="editable"
          hidden={history.location.state.reviewState == 1}
          disabled={(!ischange || record.isMax == 0) && history.location.state.reviewState == 2}
          onClick={() => {
            if (
              history.location.state.reviewState == 0 ||
              history.location.state.reviewState == 3
            ) {
              // 待审批或者已审批状态，可以随意修改bom
              setModalVisit(true);
              setCreateOrUpdate(true);
              setFormTitle('编辑');
              form.setFieldsValue({
                archiveFlag: record.archiveFlag,
                bomCode: record.bomCode,
                bomSequence: record.bomSequence,
                changeStatus: record.changeStatus,
                isolation: record.isolation,
                materialCode: record.materialCode,
                materialName: record.materialName,
                materialQty: record.materialQty,
                materialSpec: record.materialSpec,
                partCode: record.partCode,
                positionNo: record.positionNo,
                productCode: record.productCode,
                tenantId: record.tenantId,
                unit: record.unit,
                id: record.id,
                brand: record.brand,
                materialClassification: record.materialClassification,
                materialType: record.materialType,
                isJia: record.isJia,
                isMax: record.isMax,
              });
            } else if (ischange && record.isMax == 1) {
              action?.startEditable?.(record.id);
            }
          }}
        >
          编辑
        </a>,
      ],
    }, */
  ];

  const handleDelete = async (record: any) => {
    Modal.confirm({
      title: '删除物料',
      content: '确定删除',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        let ids = new Array();
        ids.push(record.id);
        console.log(typeof record.id);
        const result = await delBomReviewByIds(ids);
        console.log(result);
        if (result.code === 0) {
          message.success('删除成功');
          setReviewWithoutPostId([]);
          actionRef.current!.reload();
        } else {
          message.error('删除失败');
        }
      },
      onCancel: () => {},
    });
  };

  const handleBlur = async (record: any) => {
    const temp: any = record;
    Modal.confirm({
      title: '变更数量',
      content: '确认变更',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        if (record.materialQty === inputValue) {
          message.error('变更后的数量不能与原始数量相同');
          record.materialQty = temp.materialQty;
          setInputValue(0);
          setEditingCell(null);
        } else {
          let res = { ...ChangedItemTemplate };
          const arr = Object.keys(res);
          for (let i in arr) {
            res[arr[i]] = record[arr[i]];
          }
          res.bomBeforeId = record.id;
          res.materialQty = inputValue;
          res.id = '';
          res.changeSuccess = 0;
          res.memo = '';
          res.projectName = history.location.state.projectName;
          res.changeStatus = 3;
          res.versionSecond = record.versionSecond != null ? record.versionSecond : 0;
          res.preMaterialQty = record.materialQty;
          console.log(res);
          const result = await addBomReview(res);
          if (result.code === 0) {
            message.success('变更成功');
            setInputValue(0);
            setEditingCell(null);
            setReviewWithoutPostId([]);
            actionRef.current!.reload();
          } else {
            message.error('变更失败');
          }
        }
      },
      onCancel: () => {
        record.materialQty = temp.materialQty;
        setInputValue(0);
        setEditingCell(null);
      },
    });
  };

  // 选中项目，导出工时模板
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: string[]) => {
      const temp = [];
      if (selectedRows !== null) {
        selectedRows.map((item) => {
          temp.push(item);
        });
      }
      setSelections(temp); //保存项目信息
    },
    getCheckboxProps: (record) => {
      if (record.changeStatus === 0) {
        return { disabled: true };
      } else {
        return null;
      }
    },
  };

  //把得到的物料进行分类（原始、变更、新增）（变更中已经提交了的，变更了未提交的）
  function ClarifyResult(result) {
    const resultOverview = result.data.overview.content; //原始的
    const resultReview = result.data.review.content; //已经提交的变更或新增
    const resultReviewWithoutPost = result.data.reviewWithoutPost.content; //未提交的变更或新增
    let tempReviewWithoutPostId = new Array(); //暂时保存没有被提交的id
    let ChangedItem: any[] = []; //用来存储变更了物料的bomBeforeId
    setLatestVersionDetail(resultOverview[0]); //需要将最新的内容存储下来，方便新建时使用
    resultReview.map((r) => {
      //如果没有bomBeforeId，那就是新增的
      if (r.bomBeforeId === null) {
        r.changeStatus = 2;
      } else {
        r.changeStatus = 1;
        ChangedItem.push(r.bomBeforeId); //把bomBeforeId存下来
      }
      //r.isSubmitted = true; //已经被提交过了
      /*       r.versionSecond = r.versionSecond === null ? 0 : r.versionSecond; */
      return r;
    });
    resultReviewWithoutPost.map((r) => {
      //如果没有bomBeforeId，那就是新增的
      if (r.bomBeforeId === null) {
        r.changeStatus = 2;
      } else {
        r.changeStatus = 1;
        ChangedItem.push(r.bomBeforeId); //把bomBeforeId存下来
      }
      //r.isSubmitted = false; //没有被提交过
      /*       r.versionSecond = r.versionSecond === null ? 0 : r.versionSecond; */
      tempReviewWithoutPostId = reviewWithoutPostId;
      tempReviewWithoutPostId.push(r.id);
      setReviewWithoutPostId(tempReviewWithoutPostId);
      return r;
    });
    resultOverview.map((r) => {
      r.changeStatus = 0; //Overview中的全部都是原始数据
      r.isChanged = ChangedItem.some((c) => c === r.id);
      return r;
    });
    resultOverview.map((r) => {
      //r.isSubmitted = false;
      /*       r.versionSecond = r.versionSecond === null ? 0 : r.versionSecond; */
      return r;
    });
    const newResultOverview = resultOverview.filter((r) => r.isChanged === false); //筛选出没有变更过的原始物料
    //const newResult = [...resultOverview, ...resultReview, ...resultReviewWithoutPost]; //全部的物料
    const newResult = [...resultReviewWithoutPost, ...resultOverview]; //不包含已经提交的物料
    return newResult;
  }

  async function handleSubmitForReview() {
    let statusFlag = true;
    let submitFlag = true;
    if (selections.length === 0) {
      message.error('请选择需要提交的物料');
    } else {
      selections.map((s) => {
        //变更或新增了的物料，才允许被提交
        if (s.changeStatus === 0) {
          statusFlag = false;
        }
        //未被提交的才可以提交
        /*         if (s.isSubmitted === true) {
          submitFlag = false;
        } */
      });
      if (statusFlag && submitFlag) {
        /*         message.success('可以提交'); */
        Modal.confirm({
          title: '提交审批',
          content: '确定提交',
          okText: '确认',
          cancelText: '取消',
          onOk: async () => {
            console.log(selections, '需要被提交的');
            console.log(reviewWithoutPostId, '所有的未提交Id');
            let ids = new Array();
            selections.map((s) => {
              ids.push(s.id);
            });
            console.log(ids, '需要被提交的id');
            let withoutPostIds = new Array();
            reviewWithoutPostId.forEach((item) => {
              if (reviewWithoutPostId.includes(item) && !ids.includes(item)) {
                withoutPostIds.push(item);
              }
            });
            console.log(withoutPostIds, '不需要被提交的');
            const result = await postBomReviewByIds({
              ids: ids,
              withoutPostIds: withoutPostIds,
            });
            setSelections([]); //清除批量选择
            setReviewWithoutPostId([]); //清除变更或新增了但是未提交的部分
            console.log(result);
            if (result.code === 0) {
              message.success('提交审批成功');
            } else {
              message.error('提交审批失败');
            }
            actionRef.current?.reload();
            actionRef.current?.clearSelected(); //清除所有被选中的
          },
        });
      } else if (!statusFlag) {
        message.error('原始物料不可以被提交');
      } else if (!submitFlag) {
        message.error('已经被提交过的物料不可以被提交');
      }
    }
  }

  //定义Tabs的子结构的数组
  const tabList: tabType[] = [
    {
      name: 'tab1',
      label: 'BOM变更',
      content: (
        <>
          <Card>
            <div>
              版本筛选：
              <Select
                style={{ width: 180 }}
                placeholder="请选择BOM版本"
                onChange={(value) => {
                  setTheversion(value);
                  console.log(value);
                  actionRef.current!.reload();
                }}
                options={allversion}
              />
            </div>
          </Card>
          <ProTable<DataSourceType>
            rowKey="id"
            headerTitle="BOM清单"
            search={false}
            actionRef={actionRef} //用于触发刷新操作等，看api
            // maxLength={5}到了最大行数，新建按钮消失
            recordCreatorProps={false}
            toolBarRender={(action, { selectedRows }) => [
              // <Button
              //   key="export_button"
              //   icon={<PlusOutlined />}
              //   onClick={() => {
              //     const filter_ref = { productCode: history.location.state.productCode };
              //     const filters = filterTran(filter_ref);
              //     exportProductBomOverview({
              //       current: 1,
              //       pageSize: 5000,
              //       filters: filters,
              //     }).then((res) => {
              //       const aLink = document.createElement('a');
              //       document.body.appendChild(aLink);
              //       aLink.style.display = 'none';
              //       aLink.href = window.URL.createObjectURL(res);
              //       aLink.setAttribute('download', `ProductBomOverview.xlsx`);
              //       aLink.click();
              //       document.body.removeChild(aLink);
              //     });
              //   }}
              //   type="primary"
              // >
              //   导出
              // </Button>,
              <div className="projectScheduleGroup">
                <span>原始：</span>
                <img src="../wks.gif" />
                <span>新增：</span>
                <img src="../zxz.gif" />
                <span>变更：</span>
                <img src="../zt.gif" />
              </div>,
              <Button
                key="back_button"
                icon={<ArrowLeftOutlined />}
                onClick={() => {
                  history.push({
                    pathname: '/design/productDesign',
                    query: {
                      tab_state: history.location.state.reviewState, //传参
                    },
                  });
                }}
                type="primary"
              >
                返回
              </Button>,
              <Button
                key="add_button"
                hidden={history.location.state.reviewState == 1}
                icon={<PlusOutlined />}
                onClick={() => {
                  setCreateOrUpdate(false);
                  setFormTitle('新建');
                  form.resetFields();
                  setModalVisit(true);
                }}
                type="primary"
              >
                新增
              </Button>,
              <Button
                key="export_button"
                icon={<PlusOutlined />}
                onClick={() => {
                  const filter_ref = { productCode: history.location.state.productCode };
                  const filters = filterTran(filter_ref);
                  exportProductBomOverview({
                    current: 1,
                    pageSize: 5000,
                    filters: filters,
                  }).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    aLink.setAttribute('download', `ProductBomOverview.xlsx`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                }}
                type="primary"
              >
                导出
              </Button>,
              <Button key="submit" type="primary" onClick={handleSubmitForReview}>
                提交审批
              </Button>,
              /*               <Button
                hidden={
                  history.location.state.reviewState == 0 ||
                  history.location.state.reviewState == 1 ||
                  history.location.state.reviewState == 3
                }
                key="change_button"
                type="primary"
                onClick={() => {
                  setischange(!ischange);
                }}
              >
                变更
              </Button>, */
              /*               <Button
                hidden={
                  history.location.state.reviewState == 0 ||
                  history.location.state.reviewState == 1 ||
                  history.location.state.reviewState == 3
                }
                key="save_button"
                type="primary"
                onClick={async () => {
                  if (ischange == false) {
                    message.warning('请先进行变更');
                  } else {
                    const ids = Array.from(new Set(id_list)); //去除重复的id（多次保存的情况）
                    const nums: any[] = [];
                    for (let i = 0; i < ids.length; i++) {
                      const current_data = dataSource.filter((item: any) => {
                        return item.id == ids[i];
                      });
                      nums.push(current_data[0].materialQty);
                    }
                    // const thedata = dataSource.filter((item: any) => {
                    //   return item.isMax == 1;
                    // });
                    // thedata.map((item: any, index: any) => {
                    //   ids.push(item.id);
                    //   nums.push(item.materialQty);
                    // });
                    console.log(ids, nums, '接口数据');
                    if (ids.length == 0) {
                      message.warning('没有修改的BOM');
                      setischange(false);
                    } else {
                      const result = await change({ ids, nums });
                      if (result != null) {
                        message.success('提交审批成功');
                        setid_list([]);
                        setischange(false);
                      }
                    }
                  }
                }}
              >
                提交
              </Button>, */
            ]}
            scroll={{ x: 2200, y: 350 }}
            columns={columns}
            pagination={{ pageSize: 100 }} //默认每一页显示100条
            request={async (params = {}, sort, filter) => {
              const maxVersionResult = await getMax({
                productCode: history.location.state.productCode,
              });
              setMaxVersion('v' + maxVersionResult.data[0] + '.' + maxVersionResult.data[1]);
              const tempVersion = theversion.split('.');
              console.log(tempVersion, 'tempVersion');
              console.log(tempVersion[0], '0');
              console.log(tempVersion[1], '1');
              const res = {
                ...params,
                productCode: history.location.state.productCode,
                version: Number(tempVersion[0]) ? Number(tempVersion[0]) : maxVersionResult.data[0],
                versionSecond:
                  tempVersion[1] != undefined ? Number(tempVersion[1]) : maxVersionResult.data[1],
              };
              const sorters = sortTran(sort);
              const filters = filterTranNew(res);
              console.log(filters, 'filters');
              /*               const result = await getProductBomOverviewByPage({
                ...params,
                current: 1,
                pageSize: 100,
                sorters: sorters,
                filters: filters,
              }); */
              const result = await getProductBomOverviewAndReviewByPage({
                ...params,
                current: 1,
                pageSize: 1000,
                sorters: sorters,
                filters: filters,
              });
              console.log(result, 'result');
              const newResult = ClarifyResult(result);
              console.log(newResult, 'newResult');
              // console.log(result.data.content);
              // 获取bom版本
              /*               const result_version = await getMax({
                productCode: history.location.state.productCode,
              });
              const get_version = [];
              get_version.push({ label: '全部', value: '' });
              for (let i = 1; i <= result_version.data; i++) {
                get_version.push({ label: 'V' + String(i), value: i });
              }
              set_allversion(get_version); */
              const resultVersion = await getAllVersion({
                productCode: history.location.state.productCode,
              });
              const Version = [];
              let majorVersion; //主版本号
              let minorVersion; //次版本号
              /*               Version.push({ label: 'v' + maxVersionResult.data[0] + '.' + maxVersionResult.data[1] , value: maxVersionResult.data[0] + '.' + maxVersionResult.data[1] }); */
              resultVersion.data.map((r) => {
                majorVersion = r[0];
                minorVersion = r[1];
                Version.push({
                  label: 'v' + majorVersion + '.' + minorVersion,
                  value: majorVersion + '.' + minorVersion,
                }); //组合主次版本号
              });
              console.log(Version, 'version1');
              //对版本进行排序
              Version.sort(function (x, y) {
                if (parseInt(x.value.split('.')[0]) > parseInt(y.value.split('.')[0])) {
                  //主版本大的排前面
                  return -1;
                } else {
                  if (parseInt(x.value.split('.')[1]) > parseInt(y.value.split('.')[1])) {
                    //主版本一样大，次版本大的排前面
                    return -1;
                  } else {
                    return 1;
                  }
                }
              });
              console.log(Version, 'version2');
              setAllversion(Version);
              return {
                data: newResult,
                total:
                  result.data.overview.totalElements +
                  result.data.review.totalElements +
                  result.data.reviewWithoutPost.totalElements,
                success: result.success,
              };
            }}
            value={dataSource}
            rowSelection={{
              selections,
              ...rowSelection,
            }}
            editable={{
              type: 'multiple',
              editableKeys,
              onSave: async (rowKey, data, row) => {
                // console.log(rowKey,'', data,'更新后的data', row,'更新前的data');
                // await waitTime(2000);
                setid_list((current) => [...current, data.id]);
              },
              onChange: setEditableRowKeys,
              actionRender: (row, config, defaultDom) => {
                return [defaultDom.save, defaultDom.cancel];
              },
            }}
          />
        </>
      ),
    },
    {
      name: 'tab2',
      label: '图纸变更',
      content: <ProductNosubmittedDrawingInfo></ProductNosubmittedDrawingInfo>,
    },
  ];

  // 新增BOM
  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      form
        .validateFields()
        .then(async () => {
          const res = { ...form.getFieldsValue() };
          res.productCode = history.location.state.productCode;
          res.isMax = 1;
          res.version = 1;
          if (history.location.state.reviewState == 0 || history.location.state.reviewState == 3) {
            //待审批或驳回页面的新增
            const result = await addProductBomOverview(res);
            if (result != null) {
              message.success('添加成功');
            }
          } else {
            //已审批页面的新增
            const getuserlist = await viewBaseInfo(null);
            res.userName = getuserlist.data.name;
            res.changeStatus = 3; //新建修改
            res.changeSuccess = 0;
            res.projectName = history.location.state.projectName;
            res.bomCode = latestVersionDetail.bomCode;
            res.version = latestVersionDetail.version;
            res.versionSecond = latestVersionDetail.versionSecond;
            console.log(res);
            const result = await addBomReview(res);
            if (result != null) {
              message.success('新增物料成功');
              form.resetFields();
            }
          }
          setConfirmLoading(false);
          setModalVisit(false);
          setReviewWithoutPostId([]);
          actionRef.current!.reload();
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    } else {
      form
        .validateFields()
        .then(async () => {
          // 编辑
          const res = { ...form.getFieldsValue() };
          res.changeStatus = 1;
          console.log(res, '编辑接口数据');
          // res.productCode = recordInfo?.productCode;
          // res.bomCode = recordInfo?.bomCode;
          // res.bomSequence  = recordInfo?.bomSequence;
          // res.materialCode = recordInfo?.materialCode;
          // res.unit  = recordInfo?.unit;
          // res.isolation = recordInfo?.isolation;
          // res.archiveFlag = recordInfo?.archiveFlag;
          const result = await updateProductBomOverview(res);
          if (result != null) {
            message.success('修改成功');
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current!.reload();
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    }
  };

  // BOM上传
  const handleSubmit2 = async () => {
    setConfirmLoading2(true);
    form
      .validateFields()
      .then(async () => {
        const res = { ...form.getFieldsValue() };
        const formData = new window.FormData();
        res.file.fileList.map((file: any) => {
          formData.append('file', file.originFileObj);
        });
        res.file = formData;
        res.productCode = history.location.state.productCode;
        res.batchProductId = history.location.state.batchProductId;
        console.log(res);
        const result = await addBomByTemplate(res);
        if (result != null && result.code == 0) {
          message.success('解析成功');
          form.resetFields();
        } else if (result != null && result.code == 110) {
          message.warning('请正确使用模板');
          form.resetFields();
        }
        setConfirmLoading2(false);
        setModalVisit2(false);
        actionRef.current!.reload();
      })
      .catch(() => {
        setConfirmLoading2(false);
      });
  };

  const onFilesChange = async (file) => {
    setFile(file);
  };
  const beforeUpload = (file) => {
    setFile(file);
    return false;
  };

  const waitTime = (time: number = 100) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(true);
      }, time);
    });
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <Tabs
        destroyInactiveTabPane
        type="card"
        animated={true}
        style={{ background: 'white' }}
        items={tabList.map((item, i) => {
          const id = String(i + 1);
          return {
            label: item.label,
            key: id,
            children: <div>{item.content}</div>,
          };
        })}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
        width={800}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '95px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="archiveFlag" name="archiveFlag" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="bomCode" name="bomCode" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="bomSequence" name="bomSequence" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="changeStatus" name="changeStatus" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="isolation" name="isolation" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="partCode" name="partCode" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="productCode" name="productCode" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="tenantId" name="tenantId" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="isMax" name="isMax" hidden={true}>
            <Input />
          </Form.Item>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                label="物料编码"
                name="materialCode"
                rules={[{ required: true, message: '请输入物料编码!' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="物料名称" name="materialName">
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                label="物料规格"
                name="materialSpec"
                rules={[{ required: true, message: '请输入物料规格!' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="物料分类" name="materialClassification">
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item label="物料种类" name="materialType">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="物料品牌" name="brand">
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                label="BOM数量"
                name="materialQty"
                rules={[{ required: true, message: '请输入BOM数量!' }]}
              >
                <InputNumber min={0} precision={0} style={{ width: 255 }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="物料单位"
                name="unit"
                rules={[{ required: true, message: '请输入物料单位!' }]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                label="位置号"
                name="positionNo"
                rules={[{ required: true, message: '请输入位置号!' }]}
                // hidden={!createOrUpdate}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="是否甲供料"
                name="isJia" //
              >
                <Select
                  placeholder="请选择是否甲供料"
                  onChange={() => {}}
                  options={[
                    { value: '是', label: '是' },
                    { value: '否', label: '否' },
                  ]}
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
      <Modal
        title="上传BOM文件"
        visible={modalVisit2}
        onOk={handleSubmit2}
        confirmLoading={confirmLoading2}
        onCancel={() => setModalVisit2(false)}
        destroyOnClose
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="上传BOM"
            name="file"
            rules={[{ required: true, message: '请上传需要解析的BOM文件!' }]}
          >
            <Upload
              accept="application"
              //listType="picture-card"
              file-list="fileList"
              customRequest={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={beforeUpload}
            >
              <Button icon={<UploadOutlined />}>上传文件</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default ProductNosubmittedBomOverview;
